package com.ivan.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ivan.cmn.listener.DictListener;
import com.ivan.cmn.mapper.DictMapper;
import com.ivan.cmn.service.DictService;
import com.ivan.model.entity.cmn.Dict;
import com.ivan.model.vo.cmn.DictEeVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Ivan
 * @date 2021/3/13 18:45
 * @Description:
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {


    /**
     * 根据dictCode查询数据列表
     * @param dictCode
     * @return
     */
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code", dictCode);
        Dict dict = baseMapper.selectOne(wrapper);
        //清空查询条件
        wrapper.clear();
        if (dict != null) {
            wrapper.eq("parent_id", dict.getId());
        }
        return baseMapper.selectList(wrapper);
    }

    /**
     * 根据数据id查询子数据列表
     * @param id
     * @return
     */
    @Override
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        List<Dict> dicts = baseMapper.selectList(wrapper);
        dicts.forEach(dict -> {
            dict.setHasChildren(this.hasChildren(dict.getId()));
        });
        return dicts;
    }

    /**
     * 判断数据是否有子数据
     * @param id
     * @return
     */
    private boolean hasChildren(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(wrapper);
        return count > 0;
    }

    /**
     * 导出数据字典
     * @param response
     * @return
     */
    @Override
    public void exportDictData(HttpServletResponse response) {
        try {
            //设置下载信息
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
//            response.setContentType("application/vnd.ms-excel");
//            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");

            //存储数据
            List<DictEeVo> list = new ArrayList<>();
            //查询数据库导出数据
            List<Dict> dicts = baseMapper.selectList(null);
            //转换数据
            dicts.forEach(dict -> {
                DictEeVo dictEeVo = new DictEeVo();
                BeanUtils.copyProperties(dict, dictEeVo);
                list.add(dictEeVo);
            });
            EasyExcel.write(response.getOutputStream(), DictEeVo.class)
                    .sheet().doWrite(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入数据字典
     * @param file
     */
    @Override
    @CacheEvict(value = "dict", allEntries = true)//数据变化后清空缓存
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据dictcode和value查询
     * @param dictCode
     * @param value
     * @return
     */
    @Override
    public String getNameByDictCodeAndValue(String dictCode, String value) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
//        if(StringUtils.isEmpty(dictCode)) {
//            //如果dictCode为空，直接根据value查询
//            wrapper.eq("value",value);
//        } else {
//            //如果dictCode不为空，根据dictCode和value查询
//            wrapper.eq("dict_code", dictCode)
//                    .eq("value",value);
//        }
        if(!StringUtils.isEmpty(value)) {
            wrapper.eq("value",value);
        }
        if(!StringUtils.isEmpty(dictCode)) {
            wrapper.eq("dict_code",dictCode);
        }
        return baseMapper.selectList(wrapper).get(0).getName();
//        if(StringUtils.isEmpty(dictCode)) {
//            //如果dictCode为空，直接根据value查询
//            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
//            wrapper.eq("value",value);
//            return baseMapper.selectOne(wrapper).getName();
//        } else {
//            //如果dictCode不为空，根据dictCode和value查询
//            //根据dictCode查询dict对象，得到dict的id值
//            Dict codeDict = this.getDictByDictCode(dictCode);
//            Long parent_id = codeDict.getId();
//            //根据parent_id和value进行查询
//            QueryWrapper<Dict> wrapper = new QueryWrapper<Dict>()
//                    .eq("parent_id", parent_id)
//                    .eq("value", value);
//            return baseMapper.selectOne(wrapper).getName();
//        }
    }

//    private Dict getDictByDictCode(String dictCode) {
//        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
//        wrapper.eq("dict_code",dictCode);
//        Dict codeDict = baseMapper.selectOne(wrapper);
//        return codeDict;
//    }
}
